package com.quectel.cms.controller.parking;


import com.quectel.cms.controller.BaseController;
import com.quectel.constant.core.parking.ParkingChargingConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.core.module.parking.dto.ParkingChargingDto;
import com.quectel.core.module.parking.dto.ParkingChargingSharingTimeDto;
import com.quectel.core.module.parking.service.ParkingChargingService;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/05/11 10:26
 */
@RestController
@RequestMapping("parkingCharging")
@Tag(name = "ParkingChargingController", description = "停车场收费配置相关api")
public class ParkingChargingController extends BaseController {

    @DubboReference
    private ParkingChargingService parkingChargingService;

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("list")
    @RequirePermissions(values = "parkingCharging:list")
    @Operation(summary = "分页获取停车场收费配置列表")
    public Response<Page<ParkingChargingDto>> list(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize
    ) {
        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        super.fillAuthorityData(request.getParams());
        int total = parkingChargingService.queryTotal(request.getParams());

        List<ParkingChargingDto> list = null;
        if (total > 0) {
            list = parkingChargingService.queryList(request.getParams());
        } else {
            list = new ArrayList<>();
        }

        Page<ParkingChargingDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<ParkingChargingDto>>ok().wrap(page);
    }

    /**
     * 编辑查询反显
     *
     * @param id
     * @return
     */
    @GetMapping("infoForEdit/{id}")
    @RequirePermissions(values = "parkingCharging:edit")
    @Operation(summary = "在编辑时根据id查询停车场收费配置详情")
    public Response<ParkingChargingDto> infoForEdit(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (parkingChargingService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ParkingChargingDto parkingChargingDto = parkingChargingService.selectById(id);

        return Response.<ParkingChargingDto>ok().wrap(parkingChargingDto);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "parkingCharging:info")
    @Operation(summary = "根据id查询停车场收费配置的详情")
    public Response<ParkingChargingDto> info(@PathVariable("id") Long id) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        if (parkingChargingService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ParkingChargingDto parkingChargingDto = parkingChargingService.selectById(id);

        return Response.<ParkingChargingDto>ok().wrap(parkingChargingDto);
    }

    /**
     * 保存
     *
     * @param parkingChargingDto
     * @return
     */
    @PostMapping("save")
    @RequirePermissions(values = "parkingCharging:edit")
    @Operation(summary = "新增停车场收费配置")
    public Response<Object> save(@RequestBody @Validated ParkingChargingDto parkingChargingDto) {

        ParkingChargingDto oldOne = parkingChargingService.selectOne(parkingChargingDto.getVillageId(), parkingChargingDto.getCarType());
        if (Objects.nonNull(oldOne)) {
            return Response.error("该小区存在该车型配置");
        }

        if (ParkingChargingConstants.ChargingTypeEnum.TIME_SHARING.getChargingType().equals(parkingChargingDto.getType())) {
            // 分时计算配置检查
            List<ParkingChargingSharingTimeDto> sharingTimeList = parkingChargingDto.getSharingTimeList();
            if (ParkingChargingConstants.WeekendSiftEnum.NO_SIFT_WEEKEND.getMode().equals(parkingChargingDto.getSiftWeekend())) {
                // 不区分周末
                if (CollectionUtils.isEmpty(sharingTimeList)) {
                    return Response.error("配置参数不足");
                }

                if (Boolean.FALSE.equals(timeShareConfCheck(sharingTimeList))) {
                    return Response.error("配置检查不通过");
                }
            } else if (ParkingChargingConstants.WeekendSiftEnum.SIFT_WEEKEND.getMode().equals(parkingChargingDto.getSiftWeekend())) {
                // 区分周末
                Map<Byte, List<ParkingChargingSharingTimeDto>> collect = sharingTimeList.parallelStream()
                        .collect(Collectors.groupingBy(ParkingChargingSharingTimeDto::getIsWeekend));
                List<ParkingChargingSharingTimeDto> noSiftList = collect.get(ParkingChargingConstants.WeekendSiftEnum.NO_SIFT_WEEKEND.getMode());
                List<ParkingChargingSharingTimeDto> siftList = collect.get(ParkingChargingConstants.WeekendSiftEnum.SIFT_WEEKEND.getMode());
                if (CollectionUtils.isEmpty(noSiftList) || CollectionUtils.isEmpty(siftList)) {
                    return Response.error("配置参数不足");
                }

                if (Boolean.FALSE.equals(timeShareConfCheck(noSiftList)) || Boolean.FALSE.equals(timeShareConfCheck(siftList))) {
                    return Response.error("配置检查不通过");
                }
            } else {
                return Response.error("区分周末类型错误");
            }
        }

        //填充基础数据
        fillSaveCommonData(parkingChargingDto);

        parkingChargingService.save(parkingChargingDto);

        return Response.ok();
    }

    /**
     * 配置检查
     * @param sharingTimeList
     * @return
     */
    private Boolean timeShareConfCheck(List<ParkingChargingSharingTimeDto> sharingTimeList) {
        sharingTimeList.sort(Comparator.comparing(ParkingChargingSharingTimeDto::getStartTime));

        if (CollectionUtils.isEmpty(sharingTimeList)) {
            return Boolean.FALSE;
        }

        if (!ParkingChargingConstants.MIN_START_TIME.equals(sharingTimeList.get(0).getStartTime())
                || !ParkingChargingConstants.MAX_END_TIME.equals(sharingTimeList.get(sharingTimeList.size() - 1).getEndTime())) {
            return Boolean.FALSE;
        }
        if (sharingTimeList.size() > 1) {
            for (int i = 1; i < sharingTimeList.size(); i++) {

                if (Objects.equals(sharingTimeList.get(i - 1).getEndTime(), sharingTimeList.get(i - 1).getStartTime())
                        || !Objects.equals(sharingTimeList.get(i - 1).getEndTime(), sharingTimeList.get(i).getStartTime())
                        || Objects.equals(sharingTimeList.get(i - 1).getEndTime(), ParkingChargingConstants.MAX_END_TIME)) {
                    return Boolean.FALSE;
                }
            }
        }

        return Boolean.TRUE;
    }

    /**
     * 修改
     *
     * @param parkingChargingDto
     * @return
     */
    @PostMapping("update")
    @RequirePermissions(values = "parkingCharging:edit")
    @Operation(summary = "根据id修改停车场收费配置")
    public Response<Object> update(@RequestBody  @Validated ParkingChargingDto parkingChargingDto) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(parkingChargingDto.getId()));
        if (parkingChargingService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        ParkingChargingDto oldOne = parkingChargingService.selectOne(parkingChargingDto.getVillageId(), parkingChargingDto.getCarType());
        if (Objects.nonNull(oldOne)
                && !oldOne.getId().equals(parkingChargingDto.getId())) {
            return Response.error("该小区存在该车型配置");
        }

        if (ParkingChargingConstants.ChargingTypeEnum.TIME_SHARING.getChargingType().equals(parkingChargingDto.getType())) {
            // 分时计算配置检查
            List<ParkingChargingSharingTimeDto> sharingTimeList = parkingChargingDto.getSharingTimeList();
            if (ParkingChargingConstants.WeekendSiftEnum.NO_SIFT_WEEKEND.getMode().equals(parkingChargingDto.getSiftWeekend())) {
                // 不区分周末
                if (CollectionUtils.isEmpty(sharingTimeList)) {
                    return Response.error("配置参数不足");
                }

                if (Boolean.FALSE.equals(timeShareConfCheck(sharingTimeList))) {
                    return Response.error("配置检查不通过");
                }
            } else if (ParkingChargingConstants.WeekendSiftEnum.SIFT_WEEKEND.getMode().equals(parkingChargingDto.getSiftWeekend())) {
                // 区分周末
                Map<Byte, List<ParkingChargingSharingTimeDto>> collect = sharingTimeList.parallelStream()
                        .collect(Collectors.groupingBy(ParkingChargingSharingTimeDto::getIsWeekend));
                List<ParkingChargingSharingTimeDto> noSiftList = collect.get(ParkingChargingConstants.WeekendSiftEnum.NO_SIFT_WEEKEND.getMode());
                List<ParkingChargingSharingTimeDto> siftList = collect.get(ParkingChargingConstants.WeekendSiftEnum.SIFT_WEEKEND.getMode());
                if (CollectionUtils.isEmpty(noSiftList) || CollectionUtils.isEmpty(siftList)) {
                    return Response.error("配置参数不足");
                }

                if (Boolean.FALSE.equals(timeShareConfCheck(noSiftList)) || Boolean.FALSE.equals(timeShareConfCheck(siftList))) {
                    return Response.error("配置检查不通过");
                }
            } else {
                return Response.error("区分周末类型错误");
            }
        }

        //填充基础数据
        fillEditCommonData(parkingChargingDto);

        parkingChargingService.updateById(parkingChargingDto);

        return Response.ok();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "parkingCharging:delete")
    @Operation(summary = "根据多条记录id批量删除停车场收费配置")
    public Response<Object> delete(@RequestBody Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : ids) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (parkingChargingService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        parkingChargingService.deleteBatch(ids);

        return Response.ok();
    }
}
